# -*- coding: utf-8 -*-

from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist

from piston.handler import AnonymousBaseHandler, BaseHandler
from piston.utils import rc
import security

from fluffycentral.repository.models import ServiceProvider, File
from fluffycentral.settings import CRKey, CRPubKey

try:
    import simplejson as json
except ImportError:
    import json

class CatchAndReturn(object):
    def __init__(self, err, response):
        self.err = err
        self.response = response

    def __call__(self, fn):
        def wrapper(*args, **kwargs):
            try:
                return fn(*args, **kwargs)
            except self.err:
                return self.response
        return wrapper

# http://domain/api/sp-list
class SPListHandler(AnonymousBaseHandler):
    allowed_methods = ('PUT',)

    def update(self, request):
        postdata = json.loads(request.raw_post_data)
        name = postdata['name']
        address = postdata['address']
        status = 'EXISTS'
        sp = None
        try:
            sp = ServiceProvider.objects.get(name = name)
        except:
            sp = ServiceProvider(name = name, address = address)
            status = 'OK'
        sp.address = address
        sp.save()
        response = {'status': status,
                    'name': name,
                    'address': address}
        return response

# http://domain/api/make-cert
class MakeCertHandler(AnonymousBaseHandler):
    allowed_methods = ('PUT',)
    
    def update(self, request):
        postdata = json.loads(request.raw_post_data)
        name = postdata['name']
        address = postdata['address']
        status = 'EXISTS'
        sp = None
        try:
            sp = ServiceProvider.objects.get(name = name)
            cert = security.generateKeys()
            sp.pubkey = security.getPublicKey(cert)
            sp.save()
            spKey = security.keyToStr(cert)
            response = {'status': "OK", 'keys': spKey}
        except:
            response = {'status': "FAIL", 'keys': ""}
        return response

# http://domain/api/file-list
class FileListHandler(AnonymousBaseHandler):
    allowed_methods = ('GET','PUT')
    
    def read(self, request):
        response = {}
        responselist = []
        filelist = File.objects.all()
        for filedata in filelist:
            filedict = {}
            filedict['name'] = filedata.name
            filedict['author'] = filedata.author
            filedict['description'] = filedata.description
            filedict['sp'] = filedata.sp.name
            filedict['sp-address'] = filedata.sp.address
            responselist.append(filedict)
        response['file-list'] = responselist
        return response
        
    def update(self, request):
        postdata = json.loads(request.raw_post_data)
        files = postdata['file-list']
        spname = postdata['service-provider']
        sp = ServiceProvider.objects.get(name = spname)
        responselist = []
        for filedata in files:
            status = 'EXISTS'
            name = filedata['name']
            author = filedata['author']
            description = filedata['description']
            newfile = None
            try:
                newfile = File.objects.get(name = name)
            except:
                newfile = File(name = name)
                status = 'OK'
            newfile.author = author
            newfile.description = description
            newfile.sp = sp
            newfile.save()
            responselist.append({'name': name, 'sp': sp.name, 'status': status})
        response = {'file-list': responselist}
        return response
